package com.sky.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.sky.constant.MessageConstant;
import com.sky.context.BaseContext;
import com.sky.dto.*;
import com.sky.entity.*;
import com.sky.exception.AddressBookBusinessException;
import com.sky.exception.OrderBusinessException;
import com.sky.exception.ShoppingCartBusinessException;
import com.sky.mapper.*;
import com.sky.reminder.OrderReminder;
import com.sky.result.PageResult;
import com.sky.service.OrderService;
import com.sky.utils.HttpClientUtil;
import com.sky.utils.WeChatPayUtil;
import com.sky.vo.OrderPaymentVO;
import com.sky.vo.OrderStatisticsVO;
import com.sky.vo.OrderSubmitVO;
import com.sky.vo.OrderVO;
import com.sky.websocket.WebSocketServer;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.*;

@Service
@Slf4j
public class OrderServiceImpl implements OrderService {
    @Autowired
    private OrderMapper orderMapper;

    @Autowired
    private AddressBookMapper addressBookMapper;

    @Autowired
    private ShoppingCartMapper shoppingCartMapper;

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private OrderDetailMapper orderDetailMapper;

    @Autowired
    private WeChatPayUtil weChatPayUtil;

    //注入websocket类
    @Autowired
    private WebSocketServer webSocketServer;

    //注入reminder管理催单
    @Autowired
    private OrderReminder orderReminder;

    //注入百度地图依赖
    @Value("${sky.shop.address}")
    private String shopAddress;

    @Value("${sky.baidu.ak}")
    private String ak;

    //定义全局变量的orders来获取orderId
    private Orders orders;


    /*
     * 用户下单
     * */
    @Override
    public OrderSubmitVO submitOrder(OrdersSubmitDTO ordersSubmitDTO) {
        Orders orders = new Orders();
        BeanUtils.copyProperties(ordersSubmitDTO, orders);
        Long userCurrentId = BaseContext.getCurrentId();
        orders.setUserId(userCurrentId);

        //处理异常信息（购物车为空或者配送地址为空）
        ShoppingCart shoppingCart = new ShoppingCart();
        shoppingCart.setUserId(userCurrentId);
        //如果购物车为空
        List<ShoppingCart> shoppingCartList = shoppingCartMapper.selectAllInfo(shoppingCart);
        if (shoppingCartList.isEmpty()) {
            throw new ShoppingCartBusinessException(MessageConstant.SHOPPING_CART_IS_NULL);
        }

        //如果配送地址为空
        AddressBook addressBook = addressBookMapper.getById(ordersSubmitDTO.getAddressBookId());
        if (addressBook == null) {
            throw new AddressBookBusinessException(MessageConstant.ADDRESS_BOOK_IS_NULL);
        }

        //检查用户收货地址是否超出配送范围
        /*checkOutOfRange(addressBook.getCityName() + addressBook.getDistrictName()
                                + addressBook.getDetail());*/

        //插入一条订单数据
        //订单号
        // 生成UUID并去除横杠
        String uuid = UUID.randomUUID().toString().replace("-", "");
        // 截取前20位作为订单号
        String orderNumber = uuid.substring(0, 20);

        orders.setNumber(orderNumber);
        orders.setStatus(Orders.PENDING_PAYMENT);
        orders.setOrderTime(LocalDateTime.now());
        orders.setPhone(addressBook.getPhone());
        orders.setAddress(addressBook.getProvinceName() + addressBook.getCityName()
                + addressBook.getDistrictName() + addressBook.getDetail());
        //TODO 用户信息还没填写，填写完要获取用户名
        //orders.setUserName();
        orders.setConsignee(addressBook.getConsignee());
        orders.setPayStatus(Orders.UN_PAID);
        this.orders = orders;

        //调用mapper插入订单数据
        orderMapper.insertOrders(orders);

        //插入n条订单明细数据（包括购物车里的餐品）
        List<OrderDetail> orderDetailList = new ArrayList<>();
        for (ShoppingCart cart : shoppingCartList) {
            OrderDetail orderDetail = new OrderDetail();
            BeanUtils.copyProperties(cart, orderDetail);
            orderDetail.setOrderId(orders.getId());
            orderDetailList.add(orderDetail);
        }

        orderDetailMapper.insertOrderDetailBatch(orderDetailList);

        //清空购物车
        shoppingCartMapper.deleteAllShoppingCart(userCurrentId);


        //封装OrderSubmitVO对象
        OrderSubmitVO orderSubmitVO = new OrderSubmitVO();
        /*orderSubmitVO.setId(orders.getId());

        orderSubmitVO.setOrderTime(orders.getOrderTime());*/
        BeanUtils.copyProperties(orders, orderSubmitVO);
        orderSubmitVO.setOrderNumber(orders.getNumber());
        orderSubmitVO.setOrderAmount(orders.getAmount());

        return orderSubmitVO;
    }

    /**
     * 订单支付
     *
     * @param ordersPaymentDTO
     * @return
     */
    public OrderPaymentVO payment(OrdersPaymentDTO ordersPaymentDTO) throws Exception {
        // 当前登录用户id
        Long userId = BaseContext.getCurrentId();
        User user = userMapper.getById(userId);

        /*//调用微信支付接口，生成预支付交易单
        JSONObject jsonObject = weChatPayUtil.pay(
                ordersPaymentDTO.getOrderNumber(), //商户订单号
                new BigDecimal(0.01), //支付金额，单位 元
                "苍穹外卖订单", //商品描述
                user.getOpenid() //微信用户的openid
        );

        if (jsonObject.getString("code") != null && jsonObject.getString("code").equals("ORDERPAID")) {
            throw new OrderBusinessException("该订单已支付");
        }*/

        JSONObject jsonObject = new JSONObject();
        jsonObject.put("code", "ORDERPAID");
        OrderPaymentVO orderPaymentVO = jsonObject.toJavaObject(OrderPaymentVO.class);
        orderPaymentVO.setPackageStr(jsonObject.getString("package"));
        Integer OrderPaidStatus = Orders.PAID;//支付状态，已支付
        LocalDateTime check_out_time = LocalDateTime.now();//更新支付时间
        Integer OrderStatus = Orders.TO_BE_CONFIRMED;  //订单状态，待接单

        orderMapper.updateStatus(OrderStatus, OrderPaidStatus, check_out_time, this.orders.getId());

        /*
         * 支付成功后，向客户端发送来单提醒
         * */
        Map map = new HashMap();
        map.put("type", 1); //1 表示该信息为来单提醒
        map.put("orderId", this.orders.getId());
        map.put("content", "订单号" + this.orders.getNumber());

        String json = JSON.toJSONString(map);
        //调用WebSocket方法，发送消息给客户端
        webSocketServer.sendToAllClient(json);

        /*OrderPaymentVO vo = jsonObject.toJavaObject(OrderPaymentVO.class);
        vo.setPackageStr(jsonObject.getString("package"));*/

        return orderPaymentVO;
    }

    /**
     * 支付成功，修改订单状态
     *
     * @param outTradeNo
     */
    public void paySuccess(String outTradeNo) {

        // 根据订单号查询订单
        Orders ordersDB = orderMapper.getByNumber(outTradeNo);

        // 根据订单id更新订单的状态、支付方式、支付状态、结账时间
        Orders orders = Orders.builder()
                .id(ordersDB.getId())
                .status(Orders.TO_BE_CONFIRMED)
                .payStatus(Orders.PAID)
                .checkoutTime(LocalDateTime.now())
                .build();

        orderMapper.update(orders);
    }

    /*
     * 查看历史订单
     * */
    @Transactional
    @Override
    public PageResult findHistoryOrders(OrdersPageQueryDTO ordersPageQueryDTO) {
        //获取到当前登陆对象的id
        Long userCurrentId = BaseContext.getCurrentId();
        Orders orders = new Orders();
        orders.setUserId(userCurrentId);
        orders.setStatus(ordersPageQueryDTO.getStatus());

        //开启pageHelper
        PageHelper.startPage(ordersPageQueryDTO.getPage(), ordersPageQueryDTO.getPageSize());
        //查询订单基本信息
        Page<Orders> page = orderMapper.selectOrders(ordersPageQueryDTO);

        //设立新集合封装返回值OrdersVO
        List<OrderVO> records = new ArrayList<>();

        if (page != null && page.getTotal() > 0) {
            for (Orders order : page) {
                //获取订单的id
                Long orderId = order.getId();
                //查询订单明细信息
                List<OrderDetail> orderDetailList = orderDetailMapper.selectOrderDetailByOrderId(orderId);
                //封装orderDishes信息
                StringBuilder orderDishes = new StringBuilder();
                for (OrderDetail orderDetail : orderDetailList) {
                    String name = orderDetail.getName();
                    Integer number = orderDetail.getNumber();
                    orderDishes.append(name).append("*").append(number).append("；");
                }

                OrderVO orderVO = new OrderVO();
                BeanUtils.copyProperties(order, orderVO);
                orderVO.setOrderDetailList(orderDetailList);
                orderVO.setOrderDishes(orderDishes.toString());

                records.add(orderVO);
            }
        }

        //封装pageResult对象
        return new PageResult(page.getTotal(), records);
    }

    /*
     * 查看订单详细信息
     * */
    @Transactional
    @Override
    public OrderVO findOrderById(Long id) {
        Orders orders = new Orders();
        Long userCurrentId = BaseContext.getCurrentId();
        orders.setUserId(userCurrentId);
        orders.setId(id);

        //查看订单基本信息
        Orders order = orderMapper.selectOrderById(id);

        //查看订单菜品详细信息
        List<OrderDetail> orderDetailList = orderDetailMapper.selectOrderDetailByOrderId(id);

        //封装OrderVO对象
        OrderVO orderVO = new OrderVO();
        if (orderDetailList != null && !orderDetailList.isEmpty()) {

            BeanUtils.copyProperties(order, orderVO);
            orderVO.setOrderDetailList(orderDetailList);
        }

        return orderVO;

    }

    /*
     * 取消订单
     * */
    @Transactional
    @Override
    public void cancelOrderById(Long id) throws Exception {
        Orders orders = orderMapper.selectOrderById(id);

        //判断订单是否存在
        if (orders == null) {
            throw new OrderBusinessException(MessageConstant.ORDER_NOT_FOUND);
        }

        //待支付和待接单状态下，用户可直接取消订单
        Integer ordersStatus = orders.getStatus();

        //订单状态 1待付款 2待接单 3已接单 4派送中 5已完成 6已取消
        //商家已接单状态下，用户取消订单需电话沟通商家
        //派送中状态下，用户取消订单需电话沟通商家
        if (ordersStatus.equals(Orders.CONFIRMED) || ordersStatus.equals(Orders.DELIVERY_IN_PROGRESS)) {
            throw new OrderBusinessException(MessageConstant.ORDER_IS_CONFIRMED);
        }

        //如果在待接单状态下取消订单，需要给用户退款
        if(ordersStatus.equals(Orders.TO_BE_CONFIRMED)){
            /*weChatPayUtil.refund(
                    orders.getNumber(), //商户订单号
                    orders.getNumber(), //商户退款单号
                    new BigDecimal(0.01),//退款金额，单位 元
                    new BigDecimal(0.01));//原订单金额*/

            //修改订单状态为已退款
            orders.setPayStatus(Orders.REFUND);
        }

        //取消订单后需要将订单状态修改为“已取消”
        orders.setCancelTime(LocalDateTime.now());
        orders.setCancelReason(MessageConstant.USER_CANCEL);
        orders.setStatus(Orders.CANCELLED);
        //更新订单信息
        orderMapper.update(orders);
    }

    /*
    * 再来一单
    * */
    @Transactional
    @Override
    public void orderAgain(Long id) {
        Orders order = orderMapper.selectOrderById(id);
        //判断该订单是否为空
        if (order == null) {
            throw new OrderBusinessException(MessageConstant.ORDER_NOT_FOUND);
        }

        //将该订单重新添加到购物车
        Long orderId = order.getId();
        List<OrderDetail> orderDetailList = orderDetailMapper.selectOrderDetailByOrderId(orderId);
        List<ShoppingCart> shoppingCartList = new ArrayList<>();

        for (OrderDetail orderDetail : orderDetailList) {
            //构造购物车对象
            ShoppingCart shoppingCart = new ShoppingCart();

            BeanUtils.copyProperties(orderDetail, shoppingCart);
            shoppingCart.setUserId(BaseContext.getCurrentId());
            shoppingCart.setCreateTime(LocalDateTime.now());
            shoppingCartList.add(shoppingCart);
        }
        shoppingCartMapper.insertShopppingCartBatch(shoppingCartList);
    }

    /*
    * 统计各个状态的订单总数
    * */
    @Transactional
    @Override
    public OrderStatisticsVO statisticsOrdersByStatus() {
        //定义三个状态订单数量的总数
        Integer totalConfirmed = 0;//待派送
        Integer totalDeliverProgress = 0;//派送中
        Integer totalToBeConfirmed = 0;//待接单

        //查询所有订单信息
        OrdersPageQueryDTO ordersPageQueryDTO = new OrdersPageQueryDTO();
        Long userCurrentId = BaseContext.getCurrentId();
        ordersPageQueryDTO.setUserId(userCurrentId);
        Page<Orders> page = orderMapper.selectOrders(ordersPageQueryDTO);

        if (page != null && page.getTotal() > 0) {
            for (Orders order : page) {
                //订单状态 1待付款 2待接单 3已接单 4派送中 5已完成 6已取消
                Integer status = order.getStatus();
                if(status.equals(Orders.TO_BE_CONFIRMED)){
                    totalToBeConfirmed++;
                }else if(status.equals(Orders.CONFIRMED)){
                    totalConfirmed++;
                }else if(status.equals(Orders.DELIVERY_IN_PROGRESS)){
                    totalDeliverProgress++;
                }
            }
        }

        //封装OrderStatistics对象
        OrderStatisticsVO orderStatisticsVO = new OrderStatisticsVO();
        orderStatisticsVO.setConfirmed(totalConfirmed);
        orderStatisticsVO.setToBeConfirmed(totalToBeConfirmed);
        orderStatisticsVO.setDeliveryInProgress(totalDeliverProgress);

        return orderStatisticsVO;
    }

    /*
    * 管理端接单
    * */
    @Override
    public void takeOrder(OrdersConfirmDTO ordersConfirmDTO) {
        //商家接单其实就是将订单的状态修改为已接单
        //根据id查询该订单信息
        Orders orders = orderMapper.selectOrderById(ordersConfirmDTO.getId());

        //该订单不能为空
        if (orders == null || !orders.getStatus().equals(Orders.TO_BE_CONFIRMED)) {
            throw new OrderBusinessException(MessageConstant.ORDER_NOT_FOUND);
        }

        //修改该订单状态
        orders.setStatus(Orders.CONFIRMED);
        orderMapper.update(orders);
    }

    /*
    * 管理端拒单
    * */
    @Override
    public void rejectOrder(OrdersRejectionDTO ordersRejectionDTO) {
        //商家拒单其实就是将订单状态修改为“已取消”
        //商家拒单时需要指定拒单原因
        //获取该订单信息
        Orders orders = orderMapper.selectOrderById(ordersRejectionDTO.getId());

        if(orders == null){
            throw new OrderBusinessException(MessageConstant.ORDER_NOT_FOUND);
        }

        //只有订单处于“待接单”状态时可以执行拒单操作
        if(!orders.getStatus().equals(Orders.TO_BE_CONFIRMED)){
            throw new OrderBusinessException(MessageConstant.ORDER_STATUS_ERROR);
        }

        //商家拒单时，如果用户已经完成了支付，需要为用户退款
        //支付状态
        Integer payStatus = orders.getPayStatus();
        if (payStatus.equals(Orders.PAID)) {
            //用户已支付，需要退款
            /*String refund = weChatPayUtil.refund(
                    orders.getNumber(),
                    orders.getNumber(),
                    new BigDecimal(0.01),
                    new BigDecimal(0.01));*/
            log.info("申请退款");
            //修改订单状态为已退款
            orders.setPayStatus(Orders.REFUND);
        }

        //更新订单信息
        orders.setStatus(Orders.CANCELLED);
        orders.setCancelReason(MessageConstant.ADMIN_REJECTION);
        orders.setCancelTime(LocalDateTime.now());
        orders.setRejectionReason(ordersRejectionDTO.getRejectionReason());
        orderMapper.update(orders);
    }

    /*
    * 管理端取消订单
    * */
    @Override
    public void cancelOrder(OrdersCancelDTO ordersCancelDTO) {
        //取消订单其实就是将订单状态修改为“已取消”
        //商家取消订单时需要指定取消原因
        //商家取消订单时，如果用户已经完成了支付，需要为用户退款
        Orders orders = orderMapper.selectOrderById(ordersCancelDTO.getId());

        if(orders == null ){
            throw new OrderBusinessException(MessageConstant.ORDER_NOT_FOUND);
        }
        /*//当订单完成时，也不能取消订单
        if(orders.getStatus().equals(Orders.COMPLETED)){
            throw new OrderBusinessException(MessageConstant.ORDER_STATUS_ERROR);
        }*/

        //商家取消时，如果用户已经完成了支付，需要为用户退款
        //支付状态
        Integer payStatus = orders.getPayStatus();
        if (payStatus.equals(Orders.PAID)) {
            //用户已支付，需要退款
            /*String refund = weChatPayUtil.refund(
                    orders.getNumber(),
                    orders.getNumber(),
                    new BigDecimal(0.01),
                    new BigDecimal(0.01));*/
            log.info("申请退款");
            //修改订单状态为已退款
            orders.setPayStatus(Orders.REFUND);
        }

        //更新订单信息
        orders.setStatus(Orders.CANCELLED);
        orders.setCancelReason(ordersCancelDTO.getCancelReason());
        orders.setCancelTime(LocalDateTime.now());
        orderMapper.update(orders);
    }

    /*
    * 派送订单
    * */
    @Override
    public void deliveryOrder(Long id) {
        //判断订单是否为空
        Orders order = orderMapper.selectOrderById(id);
        if(order == null || !order.getStatus().equals(Orders.CONFIRMED)){
            throw new OrderBusinessException(MessageConstant.ORDER_NOT_FOUND);
        }

        //修改订单信息
        order.setStatus(Orders.DELIVERY_IN_PROGRESS);
        orderMapper.update(order);
    }

    /*
    * 完成订单
    * */
    @Override
    public void completeOrder(Long id) {
        //判断订单是否为空
        Orders order = orderMapper.selectOrderById(id);
        if(order == null || !order.getStatus().equals(Orders.DELIVERY_IN_PROGRESS)){
            throw new OrderBusinessException(MessageConstant.ORDER_NOT_FOUND);
        }

        //修改订单信息
        order.setStatus(Orders.COMPLETED);
        order.setDeliveryTime(LocalDateTime.now());
        orderMapper.update(order);
    }

    /*
    * 用户催单
    * */
    @Override
    public void reminderOrder(Long id) {
        //查询该订单信息
        Orders order = orderMapper.selectOrderById(id);
        Long userId = BaseContext.getCurrentId();

        //检查用户催单频率
        orderReminder.checkReminderFrequency(userId);

        //处理异常状态
        if(order == null){
            throw new OrderBusinessException(MessageConstant.ORDER_NOT_FOUND);
        }

        Map map = new HashMap();
        map.put("type", 2); //2 表示该订单为催单消息
        map.put("orderId", id);
        map.put("content", "订单号：" + order.getNumber());

        // 记录本次催单时间
        orderReminder.recordReminderTime(userId);

        //发送催单提醒到客户端
        String json = JSON.toJSONString(map);
        webSocketServer.sendToAllClient(json);
    }



    /* *//**
     * 检查客户的收货地址是否超出配送范围
     * @param address
     *//*
    private void checkOutOfRange(String address) {
        log.info("开始验证用户地址规范");

        Map map = new HashMap();
        map.put("address",shopAddress);
        map.put("output","json");
        map.put("ak",ak);

        //获取店铺的经纬度坐标
        String shopCoordinate = HttpClientUtil.doGet("https://api.map.baidu.com/geocoding/v3", map);

        JSONObject jsonObject = JSON.parseObject(shopCoordinate);
        if(!jsonObject.getString("status").equals("0")){
            throw new OrderBusinessException(MessageConstant.STORE_ADDRESS_PARSING_FAILED);
        }

        //数据解析
        JSONObject location = jsonObject.getJSONObject("result").getJSONObject("location");
        String lat = location.getString("lat");
        String lng = location.getString("lng");
        //店铺经纬度坐标
        String shopLngLat = lat + "," + lng;

        map.put("address",address);
        //获取用户收货地址的经纬度坐标
        String userCoordinate = HttpClientUtil.doGet("https://api.map.baidu.com/geocoding/v3", map);

        jsonObject = JSON.parseObject(userCoordinate);
        if(!jsonObject.getString("status").equals("0")){
            throw new OrderBusinessException(MessageConstant.RECEIVING_ADDRESS_PARSING_FAILED);
        }

        //数据解析
        location = jsonObject.getJSONObject("result").getJSONObject("location");
        lat = location.getString("lat");
        lng = location.getString("lng");
        //用户收货地址经纬度坐标
        String userLngLat = lat + "," + lng;

        map.put("origin",shopLngLat);
        map.put("destination",userLngLat);
        map.put("steps_info","0");

        //路线规划
        String json = HttpClientUtil.doGet("https://api.map.baidu.com/directionlite/v1/driving", map);

        jsonObject = JSON.parseObject(json);
        if(!jsonObject.getString("status").equals("0")){
            throw new OrderBusinessException(MessageConstant.DELIVERY_ROUTE_PLANNING_FAILED);
        }

        //数据解析
        JSONObject result = jsonObject.getJSONObject("result");
        JSONArray jsonArray = (JSONArray) result.get("routes");
        Integer distance = (Integer) ((JSONObject) jsonArray.get(0)).get("distance");

        if(distance > 10000){
            //配送距离超过10000米
            throw new OrderBusinessException(MessageConstant.OUT_OF_DELIVERY);
        }
    }*/

}
